package livesun.justiceeternal.retorfitP;


import android.annotation.SuppressLint;

import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import livesun.justiceeternal.BuildConfig;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitUtil {
   private static Retrofit sRetrofit;
   private static OkHttpClient sOkHttpClient;
   private static RetrofitUtil instance;

   private final static Object mRetrofitLock = new Object();
   private static OkHttpClient.Builder sClientBuilder;

   private static Retrofit getRetrofit() {
       if (sRetrofit == null) {
           synchronized (mRetrofitLock) {
               if (sRetrofit == null) {
                   sClientBuilder = new OkHttpClient().newBuilder();
                   if(BuildConfig.DEBUG){
                       HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
                       httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                       sClientBuilder.addInterceptor(httpLoggingInterceptor);
                   }
                   sClientBuilder.addInterceptor(new ErrorCodeInterceptor());
                   sClientBuilder. readTimeout(10, TimeUnit.SECONDS).
                           connectTimeout(10, TimeUnit.SECONDS).
                           sslSocketFactory(SSL.getSSLSocketFactory())//配置
                           .hostnameVerifier(SSL.getHostnameVerifier())//配置
                           .writeTimeout(10, TimeUnit.SECONDS);
                   sClientBuilder.addInterceptor(new HeadInterceptor());
                   sOkHttpClient = sClientBuilder.build();
                   sRetrofit = new Retrofit.Builder()
                           .client(sOkHttpClient)
                           .addConverterFactory(GsonConverterFactory.create())
                           .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                           .baseUrl(Request.baseUrl)
                           .build();
               }
           }
       }
       return sRetrofit;
   }

   public static RetrofitUtil getInstance() {
       if (instance == null) {
           synchronized (RetrofitUtil.class) {
               if (instance == null) {
                   instance = new RetrofitUtil();
               }
           }
       }
       return instance;
   }

   public <T> T get(Class<T> tClass) {
       return getRetrofit().create(tClass);
   }


}
